# ~*~ coding: utf-8 ~*~
from fabric2 import Connection


class SSHConnection(object):
    connections = {}

    @staticmethod
    def make_key(server):
        key = "{}_{}_{}".format(server.hostname, server.username, server.port)
        return key

    @classmethod
    def new_connection(cls, server, config):
        key = cls.make_key(server)
        connection = cls(server, config)
        conn = connection.connect()
        if not conn.is_connected:
            conn.open()
        cls.connections[key] = conn
        return conn

    @classmethod
    def remove_connection(cls, server):
        key = cls.make_key(server)
        cls.connections.pop(key, None)

    @classmethod
    def get_connection(cls, server):
        key = cls.make_key(server)
        return cls.connections.pop(key)

    def __init__(self, server, config):
        self.server = server
        self.config = config

    def connect(self):
        return Connection(host=self.server.manage_ip, user=self.server.username,
                          port=self.server.port, connect_kwargs={'password': self.server.password},
                          config=self.config)
